package com.ruoyi.questionnaire.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.questionnaire.domain.Questionnaire;
import com.ruoyi.questionnaire.domain.QuestionnaireDesignDTO;
import com.ruoyi.questionnaire.domain.QuestionnaireQuestion;
import com.ruoyi.questionnaire.service.IQuestionnaireDesignerService;
import com.ruoyi.questionnaire.service.IQuestionnaireQuestionService;
import com.ruoyi.questionnaire.service.IQuestionnaireService;
/**
 * 问卷设计工具Controller
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@RestController
@RequestMapping("/questionnaire/designer")
public class QuestionnaireDesignerController extends BaseController
{
    @Autowired
    private IQuestionnaireService questionnaireService;
    
    @Autowired
    private IQuestionnaireQuestionService questionService;

    @Autowired
    private IQuestionnaireDesignerService designerService;

    /**
     * 获取所有草稿状态的问卷列表（用于问卷选择下拉）
     */
    @PreAuthorize("@ss.hasPermi('questionnaire:designer:query')")
    @GetMapping("/drafts")
    public AjaxResult getDraftQuestionnaires() {
        List<Questionnaire> drafts = questionnaireService.selectQuestionnaireList(new Questionnaire() {{ setStatus("draft"); }});
        return success(drafts);
    }

    /**
     * 获取问卷设计详情
     */
    @PreAuthorize("@ss.hasPermi('questionnaire:designer:query')")
    @GetMapping("/detail/{id}")
    public AjaxResult getDesignData(@PathVariable("id") Long id)
    {
        // 获取问卷基本信息
        Questionnaire questionnaire = questionnaireService.selectQuestionnaireById(id);
        if (questionnaire == null) {
            return error("问卷不存在");
        }
        // 获取问卷的所有题目和选项
        List<QuestionnaireQuestion> questions = questionService.selectQuestionnaireQuestionList(id);
        // 构建设计数据
        Map<String, Object> designData = new HashMap<>();
        designData.put("questionnaire", questionnaire);
        designData.put("questions", questions);
        return success(designData);
    }

    /**
     * 保存问卷设计
     */
    @PreAuthorize("@ss.hasPermi('questionnaire:designer:save')")
    @Log(title = "保存问卷设计", businessType = BusinessType.UPDATE)
    @PostMapping("/save")
    public AjaxResult saveDesign(@RequestBody QuestionnaireDesignDTO designDTO)
    {
        String currentUser;
        try {
            currentUser = com.ruoyi.common.utils.SecurityUtils.getUsername();
        } catch (Exception e) {
            currentUser = "system_async";
        }
        final String finalCurrentUser = currentUser;
        AsyncManager.me().execute(new TimerTask() {
            @Override
            public void run() {
                try {
                    designerService.saveDesign(designDTO, finalCurrentUser);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        return success("保存任务已提交，稍后生效");
    }

    /**
     * 预览问卷
     */
    @PreAuthorize("@ss.hasPermi('questionnaire:designer:preview')")
    @GetMapping("/preview/{id}")
    public AjaxResult previewQuestionnaire(@PathVariable("id") Long id)
    {
        // 获取问卷预览数据
        Questionnaire questionnaire = questionnaireService.selectQuestionnaireById(id);
        List<QuestionnaireQuestion> questions = questionService.selectQuestionnaireQuestionList(id);
        
        Map<String, Object> previewData = new HashMap<>();
        previewData.put("questionnaire", questionnaire);
        previewData.put("questions", questions);
        
        return success(previewData);
    }

    /**
     * 获取设计模板列表
     */
    @PreAuthorize("@ss.hasPermi('questionnaire:designer:query')")
    @GetMapping("/templates")
    public AjaxResult getTemplates()
    {
        // 返回预设的问卷模板
        List<Map<String, Object>> templates = Arrays.asList(
            createTemplate(1, "客户满意度调查", "用于收集客户对产品或服务的满意度反馈", "满意度调查"),
            createTemplate(2, "员工满意度调查", "了解员工对工作环境、薪资福利等方面的满意度", "员工调查"),
            createTemplate(3, "产品需求调研", "收集用户对产品功能和需求的意见", "产品调研")
        );
        
        return success(templates);
    }
    
    /**
     * 创建模板数据
     */
    private Map<String, Object> createTemplate(int id, String name, String description, String category) {
        Map<String, Object> template = new HashMap<>();
        template.put("id", id);
        template.put("name", name);
        template.put("description", description);
        template.put("category", category);
        return template;
    }
} 